/*
 * @Author: LGX
 * @Date: 2022/5/3
 * @Description:
 */
import { Service } from 'egg';
import charCode from '@/lib/firstletter';

export default class MailListService extends Service {
  // 新增
  async addMail({ remark, address, email, phone, name }: any) {
    const { ctx } = this;
    return ctx.model.MailList.create({
      remark,
      address,
      email,
      phone,
      type: charCode(name).slice(0, 1),
      name,
    });
  }
  // 删除
  async deleteMail(id) {
    return this.ctx.model.MailList.destroy({ where: { id } });
  }
  // 修改
  async updateMail(rp, id) {
    return this.ctx.model.MailList.update(rp, { where: { id } });
  }
  // 分页查询
  async getDiary(param: any) {
    const { Op } = this.app.Sequelize;
    // console.log(param.page, param.pageSize)
    const { rows } = await this.ctx.model.MailList.findAndCountAll({
      where: {
        // name: 'cheny', // 精确查询
        type: {
          // 模糊查询
          [Op.like]: '%' + param.type + '%',
        },
      },
      // offset: (param.page - 1) * param.pageSize,
      // limit: param.pageSize,
      order: [[ 'type', 'ASC' ]],
    });

    // let typeArr = [
    //   {'A': []},
    // ] as any[]
    // 属性需要做类型断言处理
    // typeArr {'A': []} 26个字母
    const typeArr = {};
    rows.forEach((item: any) => {
      const type = item.type.toUpperCase();
      if (typeArr[type]) {
        typeArr[type].push(item.name);
      } else {
        typeArr[type] = [ item.name ];
      }
    });
    //  typeArr[type]  按26字母分组顺序排序
    // const typeArr2 = {}
    // Object.keys(typeArr)
    //   .sort()
    //   .map((key: any) => {
    //     console.log(key, 'key', typeArr[key])
    //     typeArr2[key] = typeArr[key]
    //   })
    // console.log(typeArr2)

    return {
      record: rows,
      list: typeArr,
      // currentPage: Number(param.page),
      // pageSize: param.pageSize,
      // pages: Math.ceil(count / param.pageSize),
      // total: count,
    };
  }
}
